import { login, filterRouter } from '@/api/login'
import { removeToken, setToken } from '@/utils/auth'

const user = {
  state: {
    token: '',
    name: '',
    avatar: '',
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ADDROUTERS: (state, addRouters) => {
      state.addRouters = addRouters
    },
    REMOVE_NAME: (state) => {
      state.name = null
    }
  },

  actions: {
  //  修改路由state
    AddRouter({ commit }, r ) {
      commit('SET_ADDROUTERS', r)
    },
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.userName.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          _g.saveUserInfo(response)
          //setToken(response.data.userName)
          resolve()
        }).catch(error => {
          console.log('登录失败')
          _g.clearUserInfo()//登录失败、清除掉用户缓存
          reject(error)
        })
      })
    },

    //  登出
    LogOut({ commit }, userName) {
      return new Promise((resolve) => {
        HTTP.methods.apiGet('/user/logout').then(() => {
          resolve()
        })
      })
    },

    SetUserName({commit}, uName){
      commit('SET_NAME', uName)
    },
    RemoveUserName({commit}){
      commit('REMOVE_NAME')
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        console.log('开始清除222')
        commit('SET_ADDROUTERS', '')
        sessionStorage.clear();
        removeToken()
        resolve()
      })
    }
  }
}

export default user
